package com.rainkaze.IntelliDrawNote.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.rainkaze.IntelliDrawNote.R;
import com.rainkaze.IntelliDrawNote.adapter.NotepadListAdapter;
import com.rainkaze.IntelliDrawNote.bean.Notepad;
import com.rainkaze.IntelliDrawNote.databinding.FragmentListNoteBinding;
import com.rainkaze.IntelliDrawNote.db.MyDbHelper;

import java.util.List;

public class NoteListFragment extends Fragment {

    private RecyclerView listRv;
    private NotepadListAdapter notepadListAdapter;
    public MyDbHelper myDbHelper;

    private EditText searchNoteEt;
    private Button searchButton;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_note, container, false);
        listRv = view.findViewById(R.id.listRv);
        searchNoteEt = view.findViewById(R.id.searchNoteEt);
        searchButton = view.findViewById(R.id.searchButton);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Context context = requireContext();
        myDbHelper = new MyDbHelper(context);
        notepadListAdapter = new NotepadListAdapter(this);

        listRv.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        listRv.setAdapter(notepadListAdapter);

        findAll();
        searchButton.setOnClickListener(v -> {
            String keyword = searchNoteEt.getText().toString().trim();
            if (keyword.isEmpty()) {
                findAll();
            } else {
                List<Notepad> result = myDbHelper.findNote(keyword);
                notepadListAdapter.update(result);
            }
        });
    }

    public void findAll() {
        List<Notepad> notepadList = myDbHelper.findAllNote();
        notepadListAdapter.update(notepadList);
    }
}